app.service('BaseService',['$q',function($q){
    var service = {};

    var Mission  =AV.Object.extend("Mission");
    var Order = AV.Object.extend("Order");
    // 处理订单扫码服务
    service.barscanHandle= function (uid,oid) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        async.auto({
            //第一步,根据orderid查询所有任务信息
            getMission:function(callback){
                var missionQuery = new AV.Query(Mission);
                missionQuery.equalTo('orderid',oid);
                missionQuery.find().then(function(data){
                   callback(null,data);

                });
            },
            // 第二步,判断订单状态是否是4000(已分配、未领件)、7000(已领件、未派送 )、3000(已出单、未打包),其他状态扫码不予处理
            // 普通订单与外卖订单，外卖订单是否被抢，被抢人UID是否是自己
            statusOfScan:function(callback){
                var orderQuery = new AV.Query(Order);
                orderQuery.equalTo('orderid',oid);
                orderQuery.find().then(function(res){
                    if (res.length > 0){
                        var status = res[0].get('status');
                        var type = res[0].get('type');
                        var messioned = res[0].get('messioned');
                        var messionedUser = res[0].get('messionedUser');
                        if (status == 4000 || status == 7000 || status == 3000 || status == 2500){
                            if (type == 6 || type == 7 || type == 8 ){
                                if (messioned === true){
                                    if (messionedUser == uid){
                                        return callback(null,{code:3,msg:'外卖自己已抢，领取订单'});
                                    }else{
                                        return callback(null,{code:4,msg:'外卖订单已被抢单，转接外卖订单'});
                                    }
                                }else{
                                    return callback(null,{code:2,msg:'外卖订单，未被抢，可以扫'});
                                }
                            }else{
                                return callback(null,{code:1,msg:'普通订单，状态可扫描'});
                            }
                        }else if(status == -1){
                            return callback(null,{code:8,msg:'用户已撤销订单'});
                        }else if(status == -2){
                            return callback(null,{code:9,msg:'平台已撤销订单'});
                        }
                        //else if(status == 3000){
                        //    return callback(null,{code:10,msg:'订单未打包完成，不能领取'});
                        //}
                        else{
                            return callback(null,{code:5,msg:'订单已被处理'});
                        }
                    }else{
                        return callback(null,{code:7,msg:'系统没有此订单'});
                    }
                }).catch(function(err){
                    console.log(err);
                    callback(err);
                });
            },
            startScan:["statusOfScan","getMission",function(callback,results){
                var status = results.statusOfScan.code ;
                var missionInfo = results.getMission;
                console.log(missionInfo);
                var list = {case:0,info:{}} ;
                switch(status){
                    case 1 :
                        //普通订单，可以扫描，到mission表中查找，是否存在，如果存在，查看status=0，return。status = 2 ，不处理。status = 1，转交
                        list['case'] = 1 ;
                        list['info']['status0'] = 0 ;
                        list['info']['status1'] = 0 ;
                        list['info']['isFirst'] = 1 ;
                        async.eachSeries(missionInfo,function(eachInfo,callback1){
                            if(eachInfo.get('status') == 0){
                                list['info']['status0'] = 1 ;
                            }else if(eachInfo.get('status') == 1){
                                list['info']['status1'] = 1 ;
                            }
                            list['info']['isFirst'] = 0 ;
                            //list:{case:1,info:{status0:0}}
                            callback1(null,list);
                        },function(){
                            console.log(list);
                            callback(null,list);
                        });
                        break;
                    case 2 :
                        //领单，修改order和mission表status
                        //向mission插入输入
                        list['case'] = 2 ;
                        list['info']['insertMission'] = 1;
                        list['info']['updateOrder'] = 1;
                        callback(null,list);
                        break;
                    case 3 :
                        list['case'] = 3 ;
                        list['info']['updateMission'] = 1;
                        list['info']['updateOrder'] = 1;
                        callback(null,list);
                        break;
                    case 4 :
                        list['case'] = 4 ;
                        list['info']['updateMission'] = 1;
                        list['info']['updateOrder'] = 1;
                        list['info']['insertMission'] = 1;
                        callback(null,list);
                        break;
                    case 5 :
                        list['case'] = 5 ;
                        list['info']['over'] = 1;
                        callback(null,list);
                        break;
                    case 7 :
                        list['case'] = 7 ;
                        list['info']['over'] = 1;
                        callback(null,list);
                        break;
                    case 8 :
                        list['case'] = 8 ;
                        list['info']['over'] = 1;
                        callback(null,list);
                        break;
                    case 9 :
                        list['case'] = 9 ;
                        list['info']['over'] = 1;
                        callback(null,list);
                        break;
                    case 10 :
                        list['case'] = 10 ;
                        list['info']['over'] = 1;
                        callback(null,list);
                        break;
                    default :
                        list['case'] = 6 ;
                        list['info']['over'] = 1;
                        callback(null,list);
                        break;
                }

            }],
            //修改数据库
            updaetOrder:["startScan",function(callback,results){
                var status = results.startScan.case ;
                var info = results.startScan.info;
                switch(status){
                    case 1 :
                        // 初次领单
                        // list:{case:1,info:{status0:0,status1:,isFirst:}}
                        if(info.isFirst == 1){
                            var orderQuery = new AV.Query(Order);
                            orderQuery.equalTo('orderid',oid);
                            orderQuery.first().then(function(res){
                                var syncs = res.get('syncStatus');
                                if(syncs == 0){
                                    res.set('syncStatus',2);
                                }
                                res.set('messioned',true);
                                res.set('messionedUser',uid);
                                res.set('status',7000);
                                date = new Date();
                                var time = Date.parse(date);
                                res.set('scantime',time);
                                res.save().then(function(){
                                    callback(null,{code:1,msg:'初次领单，订单状态改为已领'});
                                });
                            });
                        }else{
                            // 转交订单
                            if(info.status1 == 1){
                                var orderQuery = new AV.Query(Order);
                                orderQuery.equalTo('orderid',oid);
                                orderQuery.first().then(function(res){
                                    var syncs = res.get('syncStatus');
                                    if(syncs == 0){
                                        res.set('syncStatus',2);
                                    }
                                    res.set('messioned',true);
                                    res.set('messionedUser',uid);
                                    res.set('status',7000);
                                    date = new Date();
                                    var time = Date.parse(date);
                                    res.set('scantime',time);
                                    res.save().then(function(){
                                        callback(null,{code:2,msg:"转交订单,自己或者别人，修改订单状态为7000"});
                                    });
                                });
                            }else{
                                callback(null,{code:3,msg:'订单已处理，不可扫描'});
                            }
                        }
                        break;
                    case 2 :
                        //领单，修改order和mission表status
                        //向mission插入输入
                        var orderQuery = new AV.Query(Order);
                        orderQuery.equalTo('orderid',oid);
                        orderQuery.first().then(function(res){
                            var syncs = res.get('syncStatus');
                            if(syncs == 0){
                                res.set('syncStatus',2);
                            }
                            res.set('messioned',true);
                            res.set('messionedUser',uid);
                            res.set('status',7000);
                            date = new Date();
                            var time = Date.parse(date);
                            res.set('scantime',time);
                            res.save().then(function(){
                                callback(null,{code:1,msg:'order表修改完成'});
                            });
                        });
                        break;
                    case 3 :
                        var orderQuery = new AV.Query(Order);
                        orderQuery.equalTo('orderid',oid);
                        orderQuery.first().then(function(res){
                            var syncs = res.get('syncStatus');
                            if(syncs == 0){
                                res.set('syncStatus',2);
                            }
                            res.set('messioned',true);
                            res.set('messionedUser',uid);
                            res.set('status',7000);
                            date = new Date();
                            var time = Date.parse(date);
                            res.set('scantime',time);
                            res.save().then(function(){
                                callback(null,{code:1,msg:'order表修改完成'});
                            });
                        });
                        break;
                    case 4 :
                        var r=confirm("该外卖订单已被抢单，确认转接外卖订单吗!");
                        if (r==true) {
                            var orderQuery = new AV.Query(Order);
                            orderQuery.equalTo('orderid',oid);
                            orderQuery.first().then(function(res){
                                var syncs = res.get('syncStatus');
                                if(syncs == 0){
                                    res.set('syncStatus',2);
                                }
                                res.set('messioned',true);
                                res.set('messionedUser',uid);
                                res.set('status',7000);
                                date = new Date();
                                var time = Date.parse(date);
                                res.set('scantime',time);
                                res.save().then(function(){
                                    callback(null,{code:1,msg:'order表修改完成'});
                                });
                            });
                        }
                        else{
                            callback(null,{code:2,msg:'取消转接外卖订单!'});
                        }
                        break;
                    case 5 :
                        callback(null,{code:1,msg:"订单已被处理或未达可扫码状态"});
                        break;
                    case 7 :
                        callback(null,{code:1,msg:"系统没有此订单"});
                        break;
                    case 8 :
                        callback(null,{code:1,msg:"用户已撤销订单"});
                        break;
                    case 9 :
                        callback(null,{code:1,msg:"平台已撤销订单"});
                        break;
                    case 10 :
                        callback(null,{code:1,msg:"订单未打包完成，不能领取"});
                        break;
                    default :
                        callback(null,{code:0,msg:"出错了"});
                        break;
                }
            }],
            updateMission:["startScan","updaetOrder",function(callback,results){
                var status = results.startScan.case ;
                var info = results.startScan.info;
                var code = results.updaetOrder.code;
                switch(status){
                    case 1 :
                        // 初次领单
                        if(info.isFirst == 1){
                            var orderQuery = new AV.Query(Order);
                            orderQuery.equalTo('orderid',oid);
                            orderQuery.first().then(function(res){
                                var detail = res.attributes;
                                detail['createdAt'] = res.getCreatedAt();
                                callback(null,{code:2,isTransfer:0,insertNewMission:1,msg:'领单成功，请到我的任务中查看!',detail:detail});
                            });
                        }else{
                            // 转交订单
                            if(info.status1 == 1){
                                var missionQuery = new AV.Query(Mission);
                                missionQuery.equalTo('orderid',oid);
                                missionQuery.equalTo('status',1);
                                missionQuery.first().then(function(res){
                                    if (res.get('uid')==uid){
                                        //var detail = res.attributes;
                                        //detail['createdAt'] = res.getCreatedAt();
                                        var detail = res.get('detail');
                                        detail['status']=7000;
                                        date = new Date();
                                        var time = Date.parse(date);
                                        res.set('scantime',time);
                                        res.set('detail',detail);
                                        res.save().then(function(){
                                            callback(null,{code:1,msg:'你已领取此单，请不要重复领取!'});
                                        });
                                        //callback(null,{code:2,insertNewMission:0,msg:"你已领单，请到我的任务中查看!",detail:detail});
                                    }else{
                                        var r=confirm("该订单已被领取，确认转接订单吗!");
                                        if (r==true) {
                                            var appointmentTime = res.get('appointmentTime');
                                            res.set('status',2);
                                            res.save().then(function(){
                                                var orderQuery = new AV.Query(Order);
                                                orderQuery.equalTo('orderid', oid);
                                                orderQuery.first().then(function (res) {
                                                    var detail = res.attributes;
                                                    detail['createdAt'] = res.getCreatedAt();
                                                    callback(null, {
                                                        code: 2,
                                                        isTransfer:1,
                                                        appointmentTime:appointmentTime,
                                                        insertNewMission: 1,
                                                        msg: '转接订单成功，请到我的任务中查看!',
                                                        detail: detail
                                                    });
                                                });
                                            });
                                        }
                                    else{
                                            callback(null,{code:2,insertNewMission: 0,msg:'取消转接订单!'});
                                        }
                                    }
                                });
                            }else {
                                callback(null,{code:3,msg:'订单已被处理，不可扫描'});
                            }
                        }
                        break;
                    case 2 :
                        var orderQuery = new AV.Query(Order);
                        orderQuery.equalTo('orderid',oid);
                        orderQuery.first().then(function(res){
                            var detail = res.attributes;
                            detail['createdAt'] = res.getCreatedAt();
                            callback(null,{code:2,isTransfer:0,insertNewMission:1,msg:'你已领单，请到我的任务中查看!',detail:detail});
                        });
                        break;
                    case 3 :
                        var missionQuery = new AV.Query(Mission);
                        missionQuery.equalTo('orderid',oid);
                        missionQuery.equalTo('uid',uid);
                        missionQuery.equalTo('status',1);
                        missionQuery.first().then(function(res){
                            var detail = res.get('detail');
                            detail['status']=7000;
                            date = new Date();
                            var time = Date.parse(date);
                            res.set('scantime',time);
                            res.set('detail',detail);
                            res.save().then(function(){
                                callback(null,{code:1,msg:'你已经领取此单，请不要重复领取!'});
                            });
                        });
                        break;
                    case 4 :
                        if (code == 1){
                            var missionQuery = new AV.Query(Mission);
                            missionQuery.equalTo('orderid',oid);
                            missionQuery.equalTo('status',1);
                            missionQuery.first().then(function(res){
                                var appointmentTime = res.get('appointmentTime');
                                res.set('status',2);
                                res.save().then(function(){
                                    var orderQuery = new AV.Query(Order);
                                    orderQuery.equalTo('orderid', oid);
                                    orderQuery.first().then(function (res) {
                                        var detail = res.attributes;
                                        detail['createdAt'] = res.getCreatedAt();
                                        callback(null, {
                                            code: 2,
                                            isTransfer:1,
                                            appointmentTime:appointmentTime,
                                            insertNewMission: 1,
                                            msg: '转接外卖订单成功，请到我的任务中查看!',
                                            detail: detail
                                        });
                                    });
                                });
                            });
                        }else{
                            callback(null,{code:1,msg:'取消转接外卖订单'});
                        }
                        break;
                    case 5 :
                        callback(null,{code:1,msg:"订单已被处理或未达可扫码状态"});
                        break;
                    case 7 :
                        callback(null,{code:1,msg:"系统没有此订单"});
                        break;
                    case 8 :
                        callback(null,{code:1,msg:"用户已撤销订单"});
                        break;
                    case 9 :
                        callback(null,{code:1,msg:"平台已撤销订单"});
                        break;
                    case 10 :
                        callback(null,{code:1,msg:"订单未打包完成，不能领取"});
                        break;
                    default :
                        callback(null,{code:1,msg:"出错了"});
                        break;
                }

            }],
            updateMission2:['updateMission',function(callback,results){
                if(results.updateMission.code == 2){
                    if(results.updateMission.insertNewMission === 1){
                        var missionInfo = new Mission();
                        date = new Date();
                        var time = Date.parse(date);
                        missionInfo.set('scantime',time);
                        missionInfo.set('orderid',oid);
                        missionInfo.set('uid',uid);
                        missionInfo.set('status',1);
                        missionInfo.set('detail',results.updateMission.detail);
                        if (results.updateMission.isTransfer===1){
                            missionInfo.set('appointmentTime',results.updateMission.appointmentTime);
                        }
                        missionInfo.save().then(function(){
                            callback(null,{code:1,msg:results.updateMission.msg});
                        });
                    }else{
                        //var missionQuery = new AV.Query(Mission);
                        //missionQuery.equalTo('orderid',oid);
                        //missionQuery.equalTo('uid',uid);
                        //missionQuery.equalTo('status',1);
                        //missionQuery.first().then(function(res){
                        //    res.set('detail',results.updateMission.detail);
                        //    res.save().then(function(){
                        //        callback(null,{code:1,msg:results.updateMission.msg});
                        //    });
                        //});

                        callback(null,{code:1,msg:results.updateMission.msg});
                    }

                }else{
                    callback(null,{code:1,msg:results.updateMission.msg});
                }
            }],
            finalFun:["updateMission2",function(callback,results){
                callback(null,{code:0,msg:results.updateMission2.msg});
            }]
        },function(err,results){
            if(err){
                deferred.reject(err);
            }else{
                deferred.resolve(results.finalFun);
            }
        });
        return deferred.promise;
    };
    return service;
}]);




service.factory('receiveOrderFactory',['$q','appFactory',function($q,appFactory){

    var Order = AV.Object.extend('Order');

    var Mission = AV.Object.extend('Mission');

    return {
        rushMession:function(o){
            var q = $q.defer();
            async.waterfall([
                function(cb){
                    //查询订单状态
                    var query = new AV.Query(Order);
                    query.get(o.id).then(function(res){
                        if(res.get('messioned')===true){
                            cb({error:'手慢拉!~刷新一下再试试!'})
                        }else{
                            //更新订单状态
                            //o.set('status',RUSH_ORDER_STATUS);
                            o.set('rushTime',new Date());
                            o.set('messioned',true);
                            o.set('messionedUser',''+appFactory.getUserInfo().uid);

                            if(res.get('type')===9){
                                o.set('status',7000);
                            }

                            o.save().then(function(res){
                                cb(null,res);
                            }).catch(function(err){
                                cb(err);
                            });
                        }
                    }).catch(function(err){
                        cb({error:'手慢拉!~刷新一下再试试!'})
                    });
                },
                function(arg0,cb){
                    var m = new Mission();
                    var detail = o.attributes;
                    detail['createdAt'] = o.getCreatedAt();
                    m.save({
                        orderid: o.get('orderid'),
                        uid: ''+appFactory.getUserInfo().uid,
                        status: 1,
                        detail: detail,
                        rushTime: new Date()
                    }).then(function(res){
                        cb(null,res);
                    }).catch(function(err){
                        //重置订单的状态
                        o.remove('messioned');
                        o.save().then(function(res){
                            cb(null,res);
                        }).catch(function(err){
                            cb(err);
                        });
                    });
                }
            ],function(err,res){
                if(err){
                    q.reject({error:'手慢拉!~刷新一下再试试!'});
                }else{
                    q.resolve(res);
                }

            });
            return q.promise;
        }
    }
}]);
service.factory('handlerReceiveOrderFactory',['$q','appFactory',function($q,appFactory){

}]);
